#include <stdio.h>
#include "sockserver.h"

SocketServer::SocketServer(int addressFamily, int type, int protocol) 
: Socket(addressFamily, type, protocol) {
}


bool SocketServer::bindPoint(int port, const char * ip) {
	struct sockaddr_in sin;
	memset(&sin, 0, sizeof(sin));
	sin.sin_family = this->addressFamily;
	sin.sin_port = htons(port);

	if (ip == NULL) {
		sin.sin_addr.s_addr = INADDR_ANY;
	} else {
		struct hostent * hp;
		if ((hp = gethostbyname(ip)) == 0) {
			perror("gethostbyname");
			return false;
		}
		sin.sin_addr.s_addr = ((struct in_addr *)(hp->h_addr))->s_addr;
	}

	if (bind(this->sockData, (struct sockaddr *)&sin, sizeof(sin)) == -1) {
		perror("bind");
		return false;
	}

	this->setIpAddress(ip);

	return true;
}

bool SocketServer::listenConnection(int timeout = 1) {
	if (listen(this->sockData, timeout) == -1) {
		perror("listen");
		return false;
	}
	return true;
}

SocketClient * SocketServer::acceptConnection() {
	SOCKET sockData = INVALID_SOCKET;
	struct sockaddr_in pin;
	ADDRLEN_TYPE addrlen = sizeof(pin);
	if ((sockData = accept(this->sockData, (struct sockaddr *)&pin, &addrlen)) != INVALID_SOCKET) {
		SocketClient * client = new SocketClient(this->addressFamily, this->type, this->protocol);
		client->setIpAddress(inet_ntoa(pin.sin_addr));
		client->setSockData(sockData);
		return client;
	}
	perror("accept");
	return NULL;
}
